package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.expressme.openid.Association;
import org.expressme.openid.Authentication;
import org.expressme.openid.Endpoint;
import org.expressme.openid.OpenIdException;
import org.expressme.openid.OpenIdManager;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class MyAuthenticator extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware, ApplicationAware{

	@Override
	public void setApplication(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setSession(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		
	}
	
	static final long ONE_HOUR = 3600000L;
    static final long TWO_HOUR = ONE_HOUR * 2L;
    static final String ATTR_MAC = "openid_mac";
    static final String ATTR_ALIAS = "openid_alias";

    private OpenIdManager manager;
    private String url;
    private String op;
    public String execute(){
    	
    	HttpServletRequest request  = (HttpServletRequest) ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
	
		javax.servlet.http.HttpSession sess = request.getSession();
    	
    	
    	
    	manager = new OpenIdManager();
        manager.setRealm("http://localhost:8080/");
        manager.setReturnTo("http://localhost:8080/myfamilyview2/openid");
        
        if (op==null) {
            // check sign on result from Google or Yahoo:
            checkNonce(request.getParameter("openid.response_nonce"));
            // get authentication:
            byte[] mac_key = (byte[]) request.getSession().getAttribute(ATTR_MAC);
            String alias = (String) request.getSession().getAttribute(ATTR_ALIAS);
            Authentication authentication = manager.getAuthentication(request, mac_key, alias);
            request.getSession().setAttribute("authentication",authentication);
            url = "http://localhost:8080/myfamilyview2/ShowAuthenticationResult?authId="+authentication.getIdentity().split("=")[1]+"&&name="+authentication.getFullname(); 
           System.out.println(authentication.toString());
           
           System.out.println( authentication.getIdentity().split("=")[1]);
            // response.sendRedirect(url);
            /*response.setContentType("text/html; charset=UTF-8");
            showAuthentication(response.getWriter(), authentication);
            return;*/
            return "redirect";
        }
        if (op.equals("Google") || op.equals("Yahoo")) {
            
            Endpoint endpoint = manager.lookupEndpoint(op);
            System.out.println(endpoint.toString());
            Association association = manager.lookupAssociation(endpoint);
            System.out.println(association.toString());
            request.getSession().setAttribute(ATTR_MAC, association.getRawMacKey());
            request.getSession().setAttribute(ATTR_ALIAS, endpoint.getAlias());
            url = manager.getAuthenticationUrl(endpoint, association);
            //response.sendRedirect(url);
            
            return "redirect";
        }
    	
        return "redirect";
    	
    }
    
   void checkNonce(String nonce) {
        // check response_nonce to prevent replay-attack:
        if (nonce==null || nonce.length()<20)
            throw new OpenIdException("Verify failed.");
        // make sure the time of server is correct:
        long nonceTime = getNonceTime(nonce);
        long diff = Math.abs(System.currentTimeMillis() - nonceTime);
        if (diff > ONE_HOUR)
            throw new OpenIdException("Bad nonce time.");
        if (isNonceExist(nonce))
            throw new OpenIdException("Verify nonce failed.");
        storeNonce(nonce, nonceTime + TWO_HOUR);
    }

    // simulate a database that store all nonce:
    private Set<String> nonceDb = new HashSet<String>();

    // check if nonce is exist in database:
    boolean isNonceExist(String nonce) {
        return nonceDb.contains(nonce);
    }

    // store nonce in database:
    void storeNonce(String nonce, long expires) {
        nonceDb.add(nonce);
    }

    long getNonceTime(String nonce) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                    .parse(nonce.substring(0, 19) + "+0000")
                    .getTime();
        }
        catch(ParseException e) {
            throw new OpenIdException("Bad nonce time.");
        }
    }

	public OpenIdManager getManager() {
		return manager;
	}

	public void setManager(OpenIdManager manager) {
		this.manager = manager;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getOp() {
		return op;
	}

	public void setOp(String op) {
		this.op = op;
	}



}
